package com.zsrd.self.base.config;

import com.wechat.pay.contrib.apache.httpclient.WechatPayHttpClientBuilder;
import com.wechat.pay.contrib.apache.httpclient.auth.PrivateKeySigner;
import com.wechat.pay.contrib.apache.httpclient.auth.Verifier;
import com.wechat.pay.contrib.apache.httpclient.auth.WechatPay2Credentials;
import com.wechat.pay.contrib.apache.httpclient.auth.WechatPay2Validator;
import com.wechat.pay.contrib.apache.httpclient.cert.CertificatesManager;
import com.wechat.pay.contrib.apache.httpclient.util.PemUtil;
import lombok.Data;
import org.apache.http.impl.client.CloseableHttpClient;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.io.ClassPathResource;
import org.springframework.util.FileCopyUtils;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.security.PrivateKey;


@Configuration
@Data
public class WxPayConfig {



    /**
     * 商户号
     */
    private String mchId="1671631640";

    /**
     * 商户API证书序列号
     */
    private String mchSerialNo="1A3887F868BEFF4C1413BE8EE37710878A04A967";

    /**
     * 商户私钥文件地址
     */
    private String privateKeyPath="src/main/resources/apiclient_key.pem";

    /**
     * APIv3密钥
     */
    private String apiV3Key="mXnJcrHv5GHe1o2S2HIswJPjMjtsN2mo";
//    private String apiV3Key="vktdJheQlh1vSITlQef6E52wl0DB0XKL";



    /**
     * APPID
     */
    private String appid="wx687a0c10560aa623";

    /**
     *获取商户秘钥
     *@return PrivateKey
     */
    public PrivateKey getPrivateKey(String filename){
        try{
            return PemUtil.loadPrivateKey(new FileInputStream(filename));
        } catch (FileNotFoundException e){
            throw new RuntimeException("秘钥文件不存在",e);
        }
    }

    /**
     *获取微信平台签名认证器
     *@return Verifier
     */
    @Bean
    public Verifier getVerifier() throws Exception {
        File file = new File(getPath());
        String absolutePath = file.getAbsolutePath();
        //获取商户私钥
        PrivateKey privateKey = getPrivateKey(absolutePath);
        //获取签名对象
        PrivateKeySigner privateKeySigner = new PrivateKeySigner(mchSerialNo,privateKey);
        //身份认证对象
        WechatPay2Credentials wechatPay2Credentials =new WechatPay2Credentials(mchId ,privateKeySigner);
        //定时刷新微信平台的签名认证
        CertificatesManager certificatesManager = CertificatesManager.getInstance();
        // 向证书管理器增加需要自动更新平台证书的商户信息
        certificatesManager.putMerchant(mchId, wechatPay2Credentials, apiV3Key.getBytes(StandardCharsets.UTF_8));
        // 从证书管理器中获取verifier
        return certificatesManager.getVerifier(mchId);
    }


    public String getPath() throws IOException {
        // 使用 ClassPathResource 加载文件
        ClassPathResource resource = new ClassPathResource("apiclient_key.pem");

        // 将资源文件复制到临时文件
        File tempFile = File.createTempFile("tempfile", ".txt");
        try (InputStream inputStream = resource.getInputStream();
             FileOutputStream outputStream = new FileOutputStream(tempFile)) {
            FileCopyUtils.copy(inputStream, outputStream);
        }

        // 获取临时文件的绝对路径
        String absolutePath = tempFile.getAbsolutePath();
        return absolutePath;
    }

    /**
     *获取http请求对象
     *@return CloseableHttpClient
     */
    @Bean
    public CloseableHttpClient getWxpayClient(Verifier verifier) throws IOException {
        File file = new File(getPath());
        String absolutePath = file.getAbsolutePath();
        //获取商户私钥
        PrivateKey privateKey = getPrivateKey(absolutePath);
        WechatPayHttpClientBuilder builder = WechatPayHttpClientBuilder.create()
                .withMerchant(mchId, mchSerialNo, privateKey)
                .withValidator(new WechatPay2Validator(verifier));
        // ... 接下来，你仍然可以通过builder设置各种参数，来配置你的HttpClient
        // 通过WechatPayHttpClientBuilder构造的HttpClient，会自动的处理签名和验签
        //CloseableHttpResponse response = httpClient.execute();
        return builder.build();
    }
}